/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChequeDialog.java
 *
 * Created on Nov 23, 2010, 10:04:46 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleEmpresa;
import br.com.tbp.controle.ControleEndereco;
import br.com.tbp.exception.EmpresaDuplicadaException;
import br.com.tbp.exception.InputValidationException;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.Empresa;
import br.com.tbp.model.domain.Endereco;
import br.com.tbp.utils.ColorUtils;
import br.com.tbp.utils.DateUtils;
import br.com.tbp.utils.ImageUtils;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

/**
 *
 * @author Diego Freire
 */
public class EmpresaDialog extends javax.swing.JDialog {

    private JButton buscarCepButton, verificaCnpjButton, enderecoButton;
    private boolean refresh = false;
    private MenuPrincipal menu;
    private boolean novaEmpresa;
    private Empresa empresa;

    public EmpresaDialog(java.awt.Frame parent, String name, boolean modal) {
        super(parent, name, modal);
        initComponents();
        if (parent instanceof MenuPrincipal) {
            this.menu = (MenuPrincipal) parent;
        }
        cepTextField.add(getCepButton(), "After");
        cnpjTextField.add(getVerificaCnpjButton(), "After");
        logradouroTextField.add(getEnderecoButton(), "After");
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel10 = new javax.swing.JPanel();
        ativaCheckBox = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        razaoTextField = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        telefoneTextField = new javax.swing.JFormattedTextField();
        jLabel12 = new javax.swing.JLabel();
        emailTextField = new javax.swing.JTextField();
        fantasiaTextField = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        cnpjTextField = new javax.swing.JFormattedTextField();
        jLabel16 = new javax.swing.JLabel();
        inscricaoTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        representanteTextField = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        contatoTextField = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        dataCadastroTextField = new javax.swing.JFormattedTextField();
        jPanel7 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        logradouroTextField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        complementoTextField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        cepTextField = new javax.swing.JFormattedTextField();
        estadoTextField = new javax.swing.JFormattedTextField();
        bairroTextField = new javax.swing.JTextField();
        cidadeTextField = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        scrollpane = new javax.swing.JScrollPane();
        obsTextArea = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        novoButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setPreferredSize(new java.awt.Dimension(400, 40));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel9.setBackground(new java.awt.Color(255, 255, 255));
        jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/customers32.png"))); // NOI18N
        msgLabel.setText("msg");
        jPanel9.add(msgLabel);

        jPanel1.add(jPanel9, java.awt.BorderLayout.CENTER);

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 1, 1, 1));

        ativaCheckBox.setBackground(new java.awt.Color(227, 221, 221));
        ativaCheckBox.setText("Ativa");
        jPanel10.add(ativaCheckBox);

        jPanel1.add(jPanel10, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Básicas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel1.setText("ID empresa:");

        idTextField.setEditable(false);
        idTextField.setFocusable(false);

        jLabel2.setText("Razão social:");

        jLabel15.setText("Nome fantasia:");

        jLabel3.setText("Telefone:");

        try {
            telefoneTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("## - ####.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        telefoneTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel12.setText("E-mail:");

        jLabel14.setText("CNPJ:");

        try {
            cnpjTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cnpjTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        cnpjTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cnpjTextFieldActionPerformed(evt);
            }
        });

        jLabel16.setText("Inscrição estadual:");

        jLabel4.setText("Representante:");

        jLabel17.setText("Contato:");

        try {
            contatoTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("## - ####.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        contatoTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel13.setText("Data do cadastro:");

        dataCadastroTextField.setEditable(false);
        try {
            dataCadastroTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        dataCadastroTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        dataCadastroTextField.setFocusable(false);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGap(73, 73, 73)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel15)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel14))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dataCadastroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(razaoTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE)
                            .addComponent(fantasiaTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(cnpjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel16)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(inscricaoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel6Layout.createSequentialGroup()
                                .addGap(71, 71, 71)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(representanteTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel6Layout.createSequentialGroup()
                                .addGap(106, 106, 106)
                                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel12)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(telefoneTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel17)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(contatoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13)
                    .addComponent(dataCadastroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(razaoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(fantasiaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel14)
                    .addComponent(cnpjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel16)
                    .addComponent(inscricaoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(telefoneTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(representanteTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(contatoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17))
                .addGap(28, 28, 28))
        );

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Endereço", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel6.setText("Código postal (CEP):");

        jLabel7.setText("Logradouro:");

        logradouroTextField.setEditable(false);
        logradouroTextField.setFocusable(false);

        jLabel8.setText("Nº, complemento:");

        jLabel9.setText("Estado:");

        jLabel10.setText("Cidade:");

        jLabel11.setText("Bairro:");

        try {
            cepTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cepTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        cepTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cepTextFieldActionPerformed(evt);
            }
        });

        estadoTextField.setEditable(false);
        try {
            estadoTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("UU")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        estadoTextField.setFocusable(false);

        bairroTextField.setEditable(false);
        bairroTextField.setFocusable(false);

        cidadeTextField.setEditable(false);
        cidadeTextField.setFocusable(false);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(complementoTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(logradouroTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE))))
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel11)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(logradouroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(complementoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Adicionais", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel5.setText("Observações:");

        obsTextArea.setColumns(20);
        obsTextArea.setLineWrap(true);
        obsTextArea.setRows(5);
        obsTextArea.setWrapStyleWord(true);
        scrollpane.setViewportView(obsTextArea);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollpane, javax.swing.GroupLayout.DEFAULT_SIZE, 852, Short.MAX_VALUE)
                    .addComponent(jLabel5))
                .addContainerGap())
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollpane, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.BorderLayout());

        novoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/plus_16.png"))); // NOI18N
        novoButton.setMnemonic('n');
        novoButton.setText("Nova Empresa");
        novoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoButtonActionPerformed(evt);
            }
        });
        jPanel4.add(novoButton);

        jPanel3.add(jPanel4, java.awt.BorderLayout.LINE_START);

        salvarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/salvar.png"))); // NOI18N
        salvarButton.setMnemonic('s');
        salvarButton.setText("Salvar");
        salvarButton.setPreferredSize(new java.awt.Dimension(120, 26));
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        jPanel5.add(salvarButton);

        fecharButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel5.add(fecharButton);

        jPanel3.add(jPanel5, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel3, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        try {
            this.validarEntradaDoUsuario();

            ControleEmpresa controle = new ControleEmpresa();
            Empresa e = this.getEmpresa();
            if (isNovaEmpresa()) {
                controle.adicionar(e);
                msgLabel.setText("A empresa foi salva com sucesso");
                refresh(true);
            } else {
                controle.atualizar(e);
                msgLabel.setText("Os dados da empresa foram atualizados com sucesso");
                refresh(true);
            }
        } catch (InputValidationException ivex) {
            msgLabel.setText(ivex.getMessage());
            System.out.println(ivex.getMessage());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_salvarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_fecharButtonActionPerformed

    private void novoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoButtonActionPerformed
        setEmpresa(new Empresa());
        setNovaEmpresa(true);
    }//GEN-LAST:event_novoButtonActionPerformed

    private void cepTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cepTextFieldActionPerformed
        buscaCep();
    }//GEN-LAST:event_cepTextFieldActionPerformed

    private void cnpjTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cnpjTextFieldActionPerformed
        verificaCnpjDuplicado();
    }//GEN-LAST:event_cnpjTextFieldActionPerformed

    private JButton getCepButton() {
        cepTextField.setLayout(new BorderLayout());
        buscarCepButton = new JButton(ImageUtils.createIcon("search16.png"));
        buscarCepButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        buscarCepButton.setToolTipText("Informe o CEP e clique para buscar o logradouro");

        buscarCepButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                buscaCep();
            }
        });

        return buscarCepButton;
    }

    private JButton getEnderecoButton() {
        logradouroTextField.setLayout(new BorderLayout());
        enderecoButton = new JButton(ImageUtils.createIcon("add16x16.png"));
        enderecoButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        enderecoButton.setToolTipText("Clique para adicionar o endereço");

        enderecoButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                abreEndereco();
            }
        });

        return enderecoButton;
    }

    private JButton getVerificaCnpjButton() {
        cnpjTextField.setLayout(new BorderLayout());
        verificaCnpjButton = new JButton(ImageUtils.createIcon("asterisco.png"));
        verificaCnpjButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        verificaCnpjButton.setToolTipText("Informe o CNPJ e verifique se já foi utilizado");

        verificaCnpjButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                verificaCnpjDuplicado();
            }
        });

        return verificaCnpjButton;
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                EmpresaDialog dialog = new EmpresaDialog(new javax.swing.JFrame(), "TBP - Consultor", true);
                dialog.setEmpresa(new Empresa());
                dialog.setNovaEmpresa(true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox ativaCheckBox;
    private javax.swing.JTextField bairroTextField;
    private javax.swing.JFormattedTextField cepTextField;
    private javax.swing.JTextField cidadeTextField;
    private javax.swing.JFormattedTextField cnpjTextField;
    private javax.swing.JTextField complementoTextField;
    private javax.swing.JFormattedTextField contatoTextField;
    private javax.swing.JFormattedTextField dataCadastroTextField;
    private javax.swing.JTextField emailTextField;
    private javax.swing.JFormattedTextField estadoTextField;
    private javax.swing.JTextField fantasiaTextField;
    private javax.swing.JButton fecharButton;
    private javax.swing.JTextField idTextField;
    private javax.swing.JTextField inscricaoTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JTextField logradouroTextField;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton novoButton;
    private javax.swing.JTextArea obsTextArea;
    private javax.swing.JTextField razaoTextField;
    private javax.swing.JTextField representanteTextField;
    private javax.swing.JButton salvarButton;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JFormattedTextField telefoneTextField;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>

    public boolean isNovaEmpresa() {
        return novaEmpresa;
    }

    public void setNovaEmpresa(boolean n) {
        this.novaEmpresa = n;
        if (isNovaEmpresa()) {
            msgLabel.setText("Forneça os dados para a nova empresa");
            dataCadastroTextField.setText(DateUtils.getDataHojeComoString());
        } else {
            msgLabel.setText("Visualização dos dados da empresa " + this.empresa.getNomeFantasia());
        }
        razaoTextField.requestFocus();
    }

    public void validarEntradaDoUsuario() throws InputValidationException {
        if (fantasiaTextField.getText().isEmpty()) {
            fantasiaTextField.requestFocus();
            throw new InputValidationException("O nome fantasia deve ser informado");
        }
        try {
            ControleEmpresa controle = new ControleEmpresa();
            long empresaId = 0;
            if (isNovaEmpresa()) {
                empresaId = controle.verificarDuplicidade(cnpjTextField.getText());
                if (empresaId != 0) {
                    throw new EmpresaDuplicadaException("O CNPJ: " + cnpjTextField.getText()
                            + " já foi utilizado e não pode ser cadastrado novamente");
                }
            } else {
                if (cnpjTextField.getText().equals(this.objetoEmpresa().getCnpj())) {
                    return;
                } else {
                    empresaId = controle.verificarDuplicidade(cnpjTextField.getText());
                    if (empresaId != 0) {
                        throw new EmpresaDuplicadaException("O CNPJ: " + cnpjTextField.getText()
                                + " já foi utilizado e não pode ser cadastrado novamente");
                    }
                }
            }
        } catch (EmpresaDuplicadaException edex) {
            cnpjTextField.requestFocus();
            throw new InputValidationException(edex.getMessage());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    public boolean refresh() {
        return refresh;
    }

    public void refresh(boolean r) {
        this.refresh = r;
    }

    public Empresa objetoEmpresa() {
        return this.empresa;
    }

    public void mostraEnderecoUnidade(Endereco endereco) {
        if (endereco != null) {
            this.objetoEmpresa().setEndereco(endereco);
            cepTextField.setText(endereco.getCep());
            logradouroTextField.setText(endereco.getLougradouro());
            bairroTextField.setText(endereco.getBairro());
            cidadeTextField.setText(endereco.getCidade());
            estadoTextField.setText(endereco.getEstado());
            complementoTextField.setText(endereco.getComplemento());
        } else {
            limpaEndereco();
        }
    }

    public void mostraEndereco(List<Endereco> enderecoList) {
        if (enderecoList != null) {
            if (!enderecoList.isEmpty()) {
                if (enderecoList.size() == 1) {
                    Endereco endereco = enderecoList.get(0);
                    this.objetoEmpresa().setEndereco(endereco);
                    cepTextField.setText(endereco.getCep());
                    logradouroTextField.setText(endereco.getLougradouro());
                    bairroTextField.setText(endereco.getBairro());
                    cidadeTextField.setText(endereco.getCidade());
                    estadoTextField.setText(endereco.getEstado());
                    complementoTextField.setText(endereco.getComplemento());
                    complementoTextField.requestFocus();
                } else {
                    ConsultaEnderecoDialog dialog = new ConsultaEnderecoDialog(new javax.swing.JFrame(), "Endereços", true, enderecoList);
                    dialog.setVisible(true);
                    Endereco endereco = dialog.getEndereco();
                    if (endereco != null) {
                        mostraEnderecoUnidade(endereco);
                    } else {
                        limpaEndereco();
                    }
                }
            } else {
                limpaEndereco();
            }
        } else {
            limpaEndereco();
        }
    }

    private void limpaEndereco() {
        this.objetoEmpresa().setEndereco(null);
        logradouroTextField.setText(null);
        bairroTextField.setText(null);
        cidadeTextField.setText(null);
        estadoTextField.setText(null);
        complementoTextField.setText(null);
    }

    public Empresa getEmpresa() {
        empresa.setRazaoSocial(razaoTextField.getText());
        empresa.setNomeFantasia(fantasiaTextField.getText());
        empresa.setCnpj(cnpjTextField.getText());
        empresa.setInscricao(inscricaoTextField.getText());
        empresa.setTelefone(telefoneTextField.getText());
        empresa.setEmail(emailTextField.getText());
        empresa.setRepresentante(representanteTextField.getText());
        empresa.setContato(contatoTextField.getText());
        if (empresa.getEndereco() != null) {
            empresa.getEndereco().setComplemento(complementoTextField.getText());
        }
        empresa.setAtiva(ativaCheckBox.isSelected());
        empresa.setObservacoes(obsTextArea.getText());
        return empresa;
    }

    public void setEmpresa(Empresa e) {
        this.empresa = e;
        idTextField.setText("" + e.getId());
        dataCadastroTextField.setText(DateUtils.dataObjetoParaString(e.getDataDoCadastro()));
        ativaCheckBox.setSelected(e.isAtiva());
        razaoTextField.setText(e.getRazaoSocial());
        fantasiaTextField.setText(e.getNomeFantasia());
        cnpjTextField.setText(e.getCnpj());
        inscricaoTextField.setText(e.getInscricao());
        telefoneTextField.setText(e.getTelefone());
        emailTextField.setText(e.getEmail());
        representanteTextField.setText(e.getRepresentante());
        contatoTextField.setText(e.getContato());
        this.mostraEnderecoUnidade(e.getEndereco());
        obsTextArea.setText(e.getObservacoes());
        obsTextArea.setCaretPosition(0);
        if (!razaoTextField.isFocusOwner()) {
            razaoTextField.requestFocus();
        }
    }

    private void buscaCep() {
        String cep = cepTextField.getText().replace("-", "");
        ControleEndereco controle = new ControleEndereco();
        try {
            mostraEndereco(controle.pesquisar(cep));
        } catch (PersistenciaException pe) {
            System.out.println(pe.getMessage());
        }
    }

    private void verificaCnpjDuplicado() {
        try {
            ControleEmpresa controle = new ControleEmpresa();
            long empresaId = controle.verificarDuplicidade(cnpjTextField.getText());
            if (empresaId != 0) {
                throw new EmpresaDuplicadaException("O CNPJ: " + cnpjTextField.getText() + " já foi utilizado e não pode ser cadastrado novamente");
            } else {
                cnpjTextField.setForeground(ColorUtils.getVerdeEscuro());
            }
        } catch (EmpresaDuplicadaException edex) {
            cnpjTextField.setForeground(ColorUtils.getVermelhoClaro());
            JOptionPane.showMessageDialog(null, edex.getMessage(), "Informação", JOptionPane.WARNING_MESSAGE);
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    private void abreEndereco() {
        if ("     -   ".equals(cepTextField.getText())) {
            JOptionPane.showMessageDialog(null, "Informe um cep válido no campo à esquerda.", "Informação", JOptionPane.WARNING_MESSAGE);
            cepTextField.requestFocus();
            return;
        }
        String cep = cepTextField.getText();
        if (cep != null && cep.length() > 0) {
            EnderecoDialog dialog = new EnderecoDialog(menu, "TBP - Endereço", true, cep);
            dialog.setVisible(true);
            Endereco endereco = dialog.getEndereco();
            if (endereco != null) {
                try {
                    ControleEndereco controle = new ControleEndereco();
                    mostraEnderecoUnidade(controle.pesquisar(endereco.getId()));
                } catch (PersistenciaException pe) {
                    System.out.println(pe.getMessage());
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Informe um cep válido no campo à esquerda.", "Informação", JOptionPane.WARNING_MESSAGE);
            cepTextField.requestFocus();
        }
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
